import request from "../request.js"
import cfg from "../config.js"
import page from "../page.js"
import utils from "../utils.js"

//修改默认请求格式与后台匹配
function requestAdaptor(api, ignores) {
  let data = api.data;
  api.data = {
    filter: []
  }
  let keys = Object.keys(data);
  for (let key of keys) {
    if (key == 'page') {
      api.data.page = data.page;
    }
    else if (key == 'perPage') {
      api.data.perpage = data.perPage;
    }
    else if (key == 'orderBy') {
      api.data.orderby = data.orderBy;
    }
    else if (key == 'orderDir') {
      api.data.orderdir = data.orderDir;
    }
    else if (key == 'keywords') {
      api.data.keywords = data.keywords;
    }
    else {
      api.data.filter.push({
        key: key,
        value: data[key],
        like: true
      })
    }
  }
  return api;
}

let page_type = {
  open: function (page_info) {
    let page_html_id=page_info.page_html_id;
    let property=page_info.property;
    let ext_js=page_info.ext_js;
    let page_id=page_info.page_id;
    let rights=page_info.rights;
    let params=page_info.params;
    let datamodel = property.datamodel;
    let editable = property.editable;
    let id = property.id;
    let path = "datamodel/getinfo";
    request(path, { datamodel: datamodel }, function (info) {
      let tablename = info.tablename;
      let modelname = info.modelname;
      let fields = info.fields;
      let rights = info.rights;
      let r_read = rights.查 ? rights.查 : false, r_add = rights.增 ? rights.增 : false, r_edit = rights.改 ? rights.改 : false, r_del = rights.删 ? rights.删 : false;
      if (!r_read) { alert("没有数据模型：" + modelname + " 的查看权限"); return; };
      let add_form_controls_group = [];
      //对列进行排序
      fields.sort(function (a, b) {
        let a_index = 15, b_index = 15;
        if (a.name == 'id') a_index = 0;
        if (b.name == 'id') b_index = 0;
        if (a.name == 'create_time') a_index = 21;
        if (b.name == 'create_time') b_index = 21;
        if (a.name == 'create_user') a_index = 22;
        if (b.name == 'create_user') b_index = 22;
        if (a.name == 'update_time') a_index = 23;
        if (b.name == 'update_time') b_index = 23;
        if (a.name == 'update_user') a_index = 24;
        if (b.name == 'update_user') b_index = 24;
        if (a_index == 15 || b_index == 15) {
          property.columns.forEach(c => {
            if (a_index == 15 && a.name == c.name && b_index != 11) a_index = 11;
            if (b_index == 15 && b.name == c.name && a_index != 11) b_index = 11;
            if (a_index == 15 && a.name == c.name && b_index == 11) a_index = 18;
            if (b_index == 15 && b.name == c.name && a_index == 11) b_index = 18;
          })
        }
        return a_index - b_index;
      });
      for (let field of fields) { //all fields
        if (field.relater) continue; //被关联的字段不显示，源字段显示被关联字段的显示值
        let name=field.name;
        let label=(field.related && field.related.label) ? field.related.label : field.label;
        let add_form_control = {
          type: field.is_sys_field?"static":"text",
          name: name,
          label: label,
          required: field.required,
          disabled: !r_edit || !editable
        }
        if(field.is_sys_field && field.related){
          add_form_control.name="#"+name;
        }
        let property_column = property.columns ? property.columns.filter(c => c.name == field.name) : [];
        if (property_column.length > 0) {
          let prop = property_column[0];
          if(prop.type=="textarea"){
            add_form_control.type="textarea";
          }
          else if((prop.type == "number" || field.type == "number" || field.type == "int") && !field.related){
            add_form_control.type="input-number";
          }
          else if(prop.type=="date" || field.type=="date"){
            add_form_control.type="input-date";
            add_form_control.format = "YYYY-MM-DD";
            add_form_control.valueFormat = "YYYY-MM-DD";
          }
          else if(prop.type=="datetime" || field.type=="datetime"){
            add_form_control.type="input-datetime";
            add_form_control.format = "YYYY-MM-DD HH:mm:ss";
            add_form_control.valueFormat = "YYYY-MM-DD HH:mm:ss";
          }
          else if(prop.type=="switch"){
            add_form_control.type="switch";
          }
          else if(prop.type=="password" || field.type=="password"){
            add_form_control.type="input-password";
          }
          else if(prop.type=="file"){
            add_form_control.type="input-file";
            add_form_control.receiver = cfg.file_server+"upload/";
          }
          else if(prop.type=="image"){
            add_form_control.type="input-image";
            add_form_control.receiver = cfg.file_server+"upload/";
          }
          else if (prop.type == "radios") { //单选列表
            let add_and_quick_edit_set = {
              "type": "radios",
              "options": prop.options
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "checkboxes") { //多选列表
            let add_and_quick_edit_set = {
              "type": "checkboxes",
              "options": prop.options
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          } 
          else if (field.select) { //下拉选框
            let add_and_quick_edit_set = {
              "type": "select",
              "source": {
                "method": "post",
                "url": cfg.api_server + "options/get",
                "requestAdaptor": function (api) {
                  api.data={
                    group: field.select.group
                  }
                }
              }
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "icon") { //图标选择
            let edit_set = {
              "type": "picker",
              "source": "/js/icons.json",
              "valueField": "value",
              "labelField": "value",
              "size": "lg",
              "pickerSchema": {
                "mode": "cards",
                "loadDataOnce": true,
                "affixHeader": false,
                "syncLocation": false,
                "perPage": 50,
                "name": "thelist",
                "className": "icon-picker",
                "card": {
                  "body": [
                    {
                      "type": "tpl",
                      "tpl": "<i class='fa ${value}' style='font-size:1.2rem'></i>"
                    }
                  ]
                }
              }
            }
            add_form_control = Object.assign(add_form_control, edit_set); //添加时Form中的控件同编辑时的快速编辑，都是picker
          }
          else if (prop.type == "config") { //配置设置
            let api = {
              "method": "post",
              "url": cfg.api_server + "datamodel/update",
              "requestAdaptor": function (api) {
                let row = {};
                let keys = Object.keys(api.data);
                for (let key of keys) {
                  if(key!=="results"){
                    row[key] = api.data[key];
                  }
                }
                let rowDiff = api.data.diff;
                let rowOrigin = api.data.pristine;
                rowDiff.id=row.id;
                api.data = {
                  "rows": [row],
                  "rowsDiff": [rowDiff],
                  "rowsOrigin": [rowOrigin]
                }
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
              }
            };
            let language = prop.language?prop.language:"json";
            let edit_set = {
              "type": "button-toolbar",
              "buttons":[{
                "type": "button",
                "actionType": "dialog",
                "label": language.toUpperCase(),
                "icon": "fa fa-code",
                "level": "secondary",
                "size": "sm",
                "dialog": {
                  "title": "配置项编辑",
                  "size": "xl",
                  "actions": r_edit?undefined:[],
                  "body": {
                    "type": "form",
                    "name": "add-form",
                    "reload": "edit-form",
                    "className": "modal-add-form",
                    "mode": "normal",
                    "api": api,
                    "controls": [
                      {
                        type: "static",
                        name: "id",
                        label: "[ ${name} ] ID:",
                        mode: "inline"
                      },
                      {
                        type: language+"-editor",
                        "size": "xxl",
                        name: field.name,
                        disabled: !r_edit,
                        required: !field.null
                      }
                    ]
                  }
                }
              }]
            }
            add_form_control = Object.assign(add_form_control, edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (field.related) { //关联表选择
            let that_label_field = field.related.that_label_field;
            let that_field = field.related.that_field;
            let select_columns = [] //新增或者编辑选择时界面显示的列，默认包含对方关联表的关联字段和关联显示字段
            let extra_columns = prop.related ? prop.related.extra_columns : undefined //配置中的增加选择列
            let orderby = prop.related ? prop.related.orderby : undefined //配置中的关联选择时的默认排序
            let orderdir = prop.related ? prop.related.orderdir : undefined //配置中的关联选择时的默认排序
            let filterby = prop.related ? prop.related.filterby : undefined //配置中的关联选择时的默认过滤
            let filtervalue = prop.related ? prop.related.filtervalue : undefined //配置中的关联选择时的默认过滤
            if (!extra_columns || extra_columns.filter(c => c.name == that_field).length == 0) {
              select_columns.push({
                "name": that_field,
                "label": field.label,
                "sortable": true
              })
            }
            if (!extra_columns || extra_columns.filter(c => c.name == that_label_field).length == 0) {
              select_columns.push({
                "name": that_label_field,
                "label": field.related.label,
                "searchable": true,
                "sortable": true
              })
            }
            if (extra_columns) {
              extra_columns.forEach(item => { //选择时的列默认可检索
                select_columns.push({
                  "name": item.name,
                  "label": item.label,
                  "searchable": true,
                  "sortable": true
                })
              })
            }
            let edit_set = prop.related && prop.related.tree_select?
            {
              "type": "tree-select",
              "name": field.name,
              "searchable": true,
              "onlyChildren": true,
              "showIcon": false,
              "source": {
                "method": "post",
                "url": cfg.api_server + "tree/build",
                "data": {tree:prop.related.tree_select}
              }
            }
            :
            {
              "type": "picker",
              "source": {
                "method": "post",
                "url": cfg.api_server + "datamodel/getrows",
                "requestAdaptor": function (api) {
                  if (api.data.op == "loadOptions") {
                    let option_value = api.data.value;
                    api.data = {
                      filter: [{ key: that_field, value: option_value, like: false }]
                    }
                  }
                  else {
                    requestAdaptor(api, select_columns);
                  }
                  api.data.datamodel = field.related.datamodel;
                  api.data.tablename = field.related.model_table_name;
                  //默认的排序，如果没有设置，需要使用默认
                  if(!api.data.orderby && orderby){
                    api.data.orderby=orderby;
                    api.data.orderdir=orderdir;
                  }
                  //默认的过滤条件
                  if(filterby){
                    if(!api.data.filter){
                      api.data.filter=[];
                    }
                    api.data.filter.push({
                      key: filterby,
                      like: false,
                      value: filtervalue
                    })
                  }
                }
              },
              "valueField": that_field,
              "labelField": that_label_field,
              "size": "md",
              "pickerSchema": {
                "mode": "table",
                "affixHeader": false,
                "syncLocation": false,
                "perPage": 10,
                "name": "thelist",
                "columns": select_columns
              }
            }
            add_form_control = Object.assign(add_form_control, edit_set);
          }
        } //if (property_column.length > 0)
        //分组显示
        if(add_form_controls_group.length==0 || add_form_controls_group[add_form_controls_group.length-1].length>=3){
          add_form_controls_group.push([add_form_control]);
        }
        else{
          add_form_controls_group[add_form_controls_group.length-1].push(add_form_control);
        }
      } //for (let field of info.fields)
      for(let i=0;i<3-add_form_controls_group[add_form_controls_group.length-1].length;i++){
        add_form_controls_group[add_form_controls_group.length-1].push({});
      }
      let amisJSON = {
        "type": "page",
        "className": "children-edit-main-table-page",
        "body": {
          "type": "collapse",
          "title": "主记录信息",
          "body": {
            "type": "form",
            "title": "",
            "name": "edit-form",
            "submitText": r_edit && editable ?"保存":"",
            "mode": "normal",
            "initApi": {
              "method": "post",
              "url": cfg.api_server + "datamodel/getrow",
              "data": {
                "datamodel": datamodel,
                "tablename": tablename,
                "id": id
              }
            },
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/update",
              "requestAdaptor": function (api) {
                let row = {};
                let keys = Object.keys(api.data);
                for (let key of keys) {
                  if(key!=="results"){
                    row[key] = api.data[key];
                  }
                }
                let rowDiff = api.data.diff;
                let rowOrigin = api.data.pristine;
                rowDiff.id=row.id;
                utils.handlepassword(rowDiff,property.columns);
                api.data = {
                  "rows": [row],
                  "rowsDiff": [rowDiff],
                  "rowsOrigin": [rowOrigin]
                }
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
              }
            },
            "controls": add_form_controls_group
          }
        }
      }
      $("#"+page_html_id).addClass("children-edit-page");
      $("#"+page_html_id).html("<div class='main-part'></div><div class='children-part'></div>");

      let amis = amisRequire('amis/embed');
      let amisScoped = amis.embed(
        '#'+page_html_id+">.main-part", amisJSON, {},
        {
          theme: 'antd'
        }
      );
      
      let child_page_html_id="child_page_container_"+new Date().getTime();
      let tabs_html='' +
      '<div class="nav-tabs-custom">' +
        '<ul class="nav nav-tabs">' +
        '</ul>' +
        '<div class="tab-content">' +
          '<div class="tab-pane active" id="'+child_page_html_id+'"></div>' +
        '</div>' +
      '</div>';
      $("#"+page_html_id+">.children-part").html(tabs_html);


      if(property.children && property.children.length>0){
        for(let child of property.children){
          let label=child.label;
          let pageid=child.page_id;
          let that_field=child.that_field;
          let this_field=child.this_field;
          let this_field_value=child.this_field_value;
          let params={
            default_filter:[
              {
                "key": that_field,
                "value": this_field_value,
                "like": false
              }
            ]
          }

          let tab_html='<li class="child_tab_'+datamodel+'"><a href="javascript:void(0)">'+label+'</a></li>';
          $("#"+page_html_id+">.children-part>div>.nav-tabs").append(tab_html);

          $("#"+page_html_id+">.children-part>div>.nav-tabs>li:last-child").data("child_property",child);

          $("#"+page_html_id+">.children-part>div>.nav-tabs>li:last-child").click(function(){
            $("#"+page_html_id+">.children-part>div>.nav-tabs>li").removeClass("active");
            $(this).addClass("active");
            let child_property=$(this).data("child_property");
            let pageid=child_property.page_id;
            page.open(child_page_html_id,pageid,params);
          })
        }
        $("#"+page_html_id+">.children-part>div>.nav-tabs>li:first-child").click();

      }

    });
  }
}

export default page_type;